package com.yequan.thread.workerthread;

/**
 * @author yq
 * @date 2020/08/14
 */
public class Channel {

    private static final int MAX_REQUEST = 100;

    private final Request[] requestQueue;
    /**
     * 下次putRequest的位置
     */
    private int tail;
    /**
     * 下次takeRequest的位置
     */
    private int head;
    /**
     * Request的数量
     */
    private int count;

    private final WorkerThread[] threadPool;

    public Channel(int threads) {
        this.requestQueue = new Request[MAX_REQUEST];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
        threadPool = new WorkerThread[threads];
        for (int i = 0; i < threadPool.length; i++) {
            threadPool[i] = new WorkerThread("Worker-" + i, this);
        }
    }

    public void startWorkers() {
        for (int i = 0; i < threadPool.length; i++) {
            threadPool[i].start();
        }
    }

    public synchronized void putRequest(Request request) {
        try {
            while (count >= requestQueue.length) {
                wait();
            }
            requestQueue[tail] = request;
            tail = (tail + 1) % requestQueue.length;
            count++;
            notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized Request takeRequest() {
        try {
            while (count <= 0) {
                wait();
            }
            Request request = requestQueue[head];
            head = (head + 1) % requestQueue.length;
            count--;
            notifyAll();
            return request;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}
